package com.secure.core.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.secure.core.dao.IGenericDao;
import com.secure.core.entity.BaseEntity;
import com.secure.core.generate.IdGenerator;

public abstract class GenericService<T extends BaseEntity<T>, PK extends Serializable> implements IGenericService<T, PK>{
	@Autowired
	protected IdGenerator<String> idGenerator;
	
	/**
	 * @return EntityDao
	 */
	public abstract IGenericDao<T,PK> getDao();
	
	public T findById(PK id) {
		Assert.notNull(id);
		return getDao().findById(id);
	}

	public void save(T entity, boolean isIncrement) {
		Assert.notNull(entity);
		if(entity.getId()!=null){
			this.update(entity);
		}else{
			this.create(entity, isIncrement);
		}
	}
	
	private void create(T entity, boolean isIncrement) {
		Assert.notNull(entity);
		if(!isIncrement){
			entity.setId(idGenerator.generate());
		}
		getDao().insert(entity);
	}
	
	private void update(T entity) {
		Assert.notNull(entity);
		getDao().update(entity);
	}

	public void delById(PK id) {
		Assert.notNull(id);
		getDao().delById(id);
	}
	
	public List<T> quaryAll() {
		return getDao().findAll();
	}

}
